package com.xinqi.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xin麒
 * @date 2023/8/13 22:51
 */
@Configuration
public class MyJDKPoolConfig {
    @Value("${mypool.core-pool-size}")
    private int corePoolSize;
    @Value("${mypool.max-pool-size}")
    private int maxPoolSize;
//    @Resource
//    private Environment env;

    @Bean(name = "myPool")
    public Executor myPool() {
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
    }


    @Bean("qiPoolExecutor")
    public Executor qiPoolExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);

        executor.setQueueCapacity(0);
        executor.setKeepAliveSeconds(60);
        /*keepAliveTime的单位是纳秒，即1s=1000000000ns，1秒等于10亿纳秒。
keepAliveTime是线程池中空闲线程等待工作的超时时间。
当线程池中线程数量大于corePoolSize（核心线程数量）或设置了allowCoreThreadTimeOut（是否允许空闲核心线程超时）时，线程会根据keepAliveTime的值进行活性检查，一旦超时便销毁线程。
否则，线程会永远等待新的工作。https://blog.csdn.net/u010841296/article/details/89419115*/
        executor.setThreadNamePrefix("qiPoolExecutor--");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        //修改拒绝策略为使用当前线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }




}
